package cool.xinya.ess.util;

import cool.xinya.ess.security.ShiroUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class SessionUtil {

    /**
     * 获取系统地址
     */
    public static String getServerPath() {
        HttpServletRequest request = getHttpServletRequest();
        return StringUtils.replace(request.getRequestURL().toString(), request.getRequestURI(), "/");
    }

    /**
     * 获取请求request
     */
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 获取请求response
     */
    public static HttpServletResponse getHttpServletResponse() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    }

    /**
     * 获取当前用户名
     *
     * @author wangxiaolong
     * @date 2019/8/8 18:59
     */
    public static String getLoginName() {
        ShiroUser shiroUser = getShiroUser();
        if (shiroUser == null) {
            return "";
        }
        return shiroUser.getLoginName();
    }

    /**
     * 得到当前用户
     *
     * @author wangxiaolong
     * @date 2019/8/12 10:32
     */
    public static ShiroUser getShiroUser() {
        return (ShiroUser) SecurityUtils.getSubject().getPrincipal();
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession(false);
    }
}
